package com.hbnu.system.controller;

import com.hbnu.system.core.base.Rest;
import com.hbnu.system.utils.FileUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fileUpload")
@Api(tags = "文件上传")
public class FileUploadController {

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Value("${spring.servlet.multipart.max-file-size:50MB}")
    private String maxFileSize;

    @ApiOperation("纵向项目文件上传")
    @PostMapping("/uploadfilePorProject")
    public Rest<String> uploadfilePorProject(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(),"/PorProject/",file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("横向项目文件上传")
    @PostMapping("/uploadfileTranProject")
    public Rest<String> uploadfileTranProject(MultipartFile file) {
        try {
            // 添加文件校验
            Rest<String> validationResult = validateFile(file);
            if (validationResult != null) {
                return validationResult;
            }

            String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/TranProject/", file);
            return Rest.success(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Rest.failed("文件上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("专利文件上传")
    @PostMapping("/uploadfilePatent")
    public Rest<String> uploadfilePatent(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/Patent/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("论文文件上传")
    @PostMapping("/uploadfilePaper")
    public Rest<String> uploadfilePaper(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/Paper/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("著作文件上传")
    @PostMapping("/uploadfileWork")
    public Rest<String> uploadfileWork(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/Work/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("艺体文件上传")
    @PostMapping("/uploadfileArt")
    public Rest<String> uploadfileArt(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/Art/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("奖励文件上传")
    @PostMapping("/uploadfileAward")
    public Rest<String> uploadfileAward(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/Award/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("科研平台文件上传")
    @PostMapping("/uploadfileTplatform")
    public Rest<String> uploadfileTplatform(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/TPlatform/", file);
        return Rest.success(imageUrl);
    }

    @ApiOperation("科研成果文件上传")
    @PostMapping("/uploadfileAchievementFile")
    public Rest<String> uploadfileAchievementFile(MultipartFile file) throws IOException, InterruptedException {
        // 添加文件校验
        Rest<String> validationResult = validateFile(file);
        if (validationResult != null) {
            return validationResult;
        }

        String imageUrl = fileUploadUtil.uploadfile(file.getOriginalFilename(), "/AchievementFile/", file);
        return Rest.success(imageUrl);
    }

    /**
     * 统一的文件校验方法
     */
    private Rest<String> validateFile(MultipartFile file) {
        // 文件空校验
        if (file == null || file.isEmpty()) {
            return Rest.failed("请选择要上传的文件");
        }

        // 文件大小校验 - 从配置文件读取
        if (file.getSize() > 50 * 1024 * 1024) {
            return Rest.failed("文件大小不能超过50MB");
        }

        // 文件类型校验
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isValidFileType(fileName)) {
            return Rest.failed("只支持pdf, doc, docx, jpg, png格式的文件");
        }

        return null; // 校验通过
    }

    /**
     * 校验文件类型
     */
    private boolean isValidFileType(String fileName) {
        String lowerFileName = fileName.toLowerCase();
        return lowerFileName.endsWith(".pdf") ||
                lowerFileName.endsWith(".doc") ||
                lowerFileName.endsWith(".docx") ||
                lowerFileName.endsWith(".jpg") ||
                lowerFileName.endsWith(".jpeg") ||
                lowerFileName.endsWith(".png") ||
                lowerFileName.endsWith(".xlsx");
    }

    /**
     * 解析文件大小配置(支持KB, MB, GB)
     */
    private long parseSize(String size) {
        size = size.toUpperCase().trim();
        long multiplier = 1;
        
        if (size.endsWith("KB")) {
            multiplier = 1024;
            size = size.substring(0, size.length() - 2).trim();
        } else if (size.endsWith("MB")) {
            multiplier = 1024 * 1024;
            size = size.substring(0, size.length() - 2).trim();
        } else if (size.endsWith("GB")) {
            multiplier = 1024 * 1024 * 1024;
            size = size.substring(0, size.length() - 2).trim();
        }
        
        try {
            return Long.parseLong(size) * multiplier;
        } catch (NumberFormatException e) {
            return 50 * 1024 * 1024; // 默认50MB
        }
    }
}